package com.zcx.liu_zi_qi

import android.annotation.TargetApi
import android.content.Context
import android.content.Intent
import android.graphics.*
import android.os.Build
import android.os.Message
import android.util.Range
import android.view.MotionEvent
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.widget.Toast

class GameUI constructor(context:Context):SurfaceView(context),SurfaceHolder.Callback{
    private lateinit var thread:Thread//绘图线程
    private lateinit var chessBoard:ChessBoard//棋盘实例
    private var isChessable=true//标记是否可下子
    private var whoWin:ChessManType?=null//哪方获胜,null代表没有胜利者
    var isExit=false//标记是否退出游戏
    private lateinit var background:Bitmap//背景图片

    init {
        this.setZOrderOnTop(true)
        //this.setBackgroundResource(R.drawable.background)
        background=BitmapFactory.decodeResource(context.resources,R.drawable.background)
        this.holder.setFormat(PixelFormat.TRANSLUCENT)
        this.holder.addCallback(this)
        Map.list.removeAll(Map.list)
        Map.history.removeAll(Map.history)
        for (i in 0..3){
            val arr= Array<Int>(4,{it -> 0})
            for (j in 0..3){
                if(i==0||(i==1&&(j==0||j==3))){
                    arr[j]=2
                }
                if(i==3||(i==2&&(j==0||j==3))){
                    arr[j]=1
                }
            }
            Map.map[i]=arr
            Toast.makeText(context,"游戏初始化完成", Toast.LENGTH_SHORT).show()
        }
    }
    override fun surfaceChanged(holder: SurfaceHolder?, format: Int, width: Int, height: Int) {

    }

    override fun surfaceDestroyed(holder: SurfaceHolder?) {
        thread.join()
    }

    override fun surfaceCreated(holder: SurfaceHolder?) {
        thread= Thread(GameThread(holder))
        thread.start()
    }

    inner class GameThread(val holder: SurfaceHolder?):Runnable{
        override fun run() {
            while(true){
                if(isExit){
                    return
                }
                var canvas= holder?.lockCanvas()
                //canvas?.drawColor(Color.WHITE)
                canvas?.drawBitmap(background, Rect(0,0,background.width,background.height),
                    Rect(0,0,canvas.width,canvas.height),Paint())
                canvas?.let {
                    chessBoard=ChessBoard(it)
                    chessBoard.update()
                }
                holder?.unlockCanvasAndPost(canvas)
                if(whoWin!=null){
                    val msg=Message.obtain()
                    msg.what=1
                    msg.obj=whoWin
                    (context as GameActivity).handle.sendMessage(msg)
                    return
                }
            }

        }

    }

    /**
     * 监听触摸事件
     */
    override fun onTouchEvent(event: MotionEvent?): Boolean {
        val x= event?.getX()
        val y=event?.getY()
        //println("(x,y)=($x,$y)")
        if (x != null&&y!=null) {
            selectChessMan(x,y)
        }
        return true
    }

    /**
     * 下子
     */
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private fun selectChessMan(x:Float,y:Float){
        val ij=chessBoard.xy2ij(Pair(x,y))
        val i=ij?.first
        val j=ij?.second
        println("(i,j)=($i,$j)")
        synchronized(Map){//同步代码块
            isChessable=when(Map.whoChess){
                ChessManType.WHITE -> if (Map.map[i!!][j!!]!=2) true else false
                else -> if (Map.map[i!!][j!!]!=1) true else false
            }
            if(isChessable){
                Map.list.forEach {
                    if(x in Range(it.cx-100,it.cx+100)
                        && y in Range(it.cy-100,it.cy+100)){
                        Map.list.filter { it.isSelect }.forEach {
                            it.isSelect=false
                        }
                        it.isSelect=true
                    }
                }
                moveChessMan(i!!,j!!)
            }

        }

    }

    /**
     * 移动棋子
     */
    private fun moveChessMan(i:Int,j:Int){
        if(Map.map[i][j]!=0){//目标位置有子
            return
        }
        Map.list.filter { it.isSelect }.forEach {
            if(it.move(i,j)){
                //println(Map.printMap())
                it.isSelect=false
                Map.whoChess=when(Map.whoChess){
                    ChessManType.WHITE -> ChessManType.BLACK
                    else -> ChessManType.WHITE
                }
                it.check()
                val msg=Message.obtain()
                msg.what=2
                val map=kotlin.collections.HashMap<String,String>()
                map.put("blackCount",Map.list.filter { it.type==ChessManType.BLACK }.size.toString())
                map.put("whiteCount",Map.list.filter { it.type==ChessManType.WHITE }.size.toString())
                msg.obj=map
                (context as GameActivity).handle.sendMessage(msg)
                checkWin()
            }


        }

    }

    /**
     * 判断输赢
     */
    fun checkWin(){
        if(Map.list.filter { it.type==ChessManType.WHITE }.size==0){
            whoWin=ChessManType.BLACK
        }
        if(Map.list.filter { it.type==ChessManType.BLACK }.size==0){
            whoWin=ChessManType.WHITE
        }
    }

    /**
     * 退出游戏
     */
    fun exit(){
        isExit=true
        Map.whoChess=ChessManType.WHITE
        thread.join()

    }



}